package advanced.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 循环屏蔽器, 当所有线程都到达屏蔽器时, 才会执行各个线程剩下的逻辑代码
 */
public class CyclicBarrier_L {
    static int barrierCount = 20;

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(barrierCount);
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < barrierCount; i++) {
            int xi = i;
            service.execute(() -> {
                System.out.println(Thread.currentThread().getName() + xi);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + xi + " over");
//                cyclicBarrier.reset();//Resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a
            });
        }
        service.shutdown();
    }
}
